package entutil

import (
	"entgo.io/ent/entc"
	"entgo.io/ent/entc/gen"
	"fmt"
)

type GenerateConfig struct {
	Templates []*gen.Template
}

func Generate(schema string, config GenerateConfig) error {
	return entc.Generate(schema, config.config())
}
func (g GenerateConfig) config() *gen.Config {
	return &gen.Config{
		Features: []gen.Feature{
			gen.FeatureModifier,
			gen.FeatureEntQL,
		},
		Hooks: []gen.Hook{
			func(next gen.Generator) gen.Generator {
				return gen.GenerateFunc(func(g *gen.Graph) error {
					if err := next.Generate(g); err != nil {
						return fmt.Errorf("ent generate: %w", err)
					}
					for _, node := range g.Nodes {
						//node.Annotations.Set()
						if temps, ok := node.Annotations["templates"]; ok {

							tempMap := temps.([]any)
							for _, temp := range tempMap {
								if genT, ok := temp.(map[string]any); ok {
									if err := genTemplate(genT).render(node); err != nil {
										return fmt.Errorf("ent generate template: %w", err)
									}
								} else {
									return fmt.Errorf("ent generate template: not a template")
								}
							}
						}
					}
					return nil
				})
			},
		},
		Templates: g.Templates,
	}
}
